﻿// 功能：
// 描述：
// 作者：温伟鹏
// 日期：2010/10/22 14:16:46

using System;
using System.Drawing;
using System.Collections;
using System.Globalization;
using System.ComponentModel;

namespace MeizuSDK.Drawing
{
    /// <summary>
    /// 颜色转换器
    /// </summary>
    public sealed class ColorTranslator
    {
        /// <summary>
        /// 将给定的Color值转化为16进制形式的字符串。格式：0xFFFFFF
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static string ToHex(Color c)
        {
            string str = string.Empty;
            if (!c.IsEmpty)
            {
                return ("0x" + c.R.ToString("X2", null) + c.G.ToString("X2", null) + c.B.ToString("X2", null));
            }
            return str;
        }
        /// <summary>
        /// 将给定的Color值转化为HTML中的颜色格式。格式：#FFFFFF
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static string ToHtml(Color c)
        {
            string str = string.Empty;
            if (!c.IsEmpty)
            {
                return ("#" + c.R.ToString("X2", null) + c.G.ToString("X2", null) + c.B.ToString("X2", null));
            }
            return str;
        }
        /// <summary>
        /// 将给定的HTML格式的颜色值转化为Color结构实例
        /// </summary>
        /// <param name="htmlColor">格式为#FFFFFF的颜色值</param>
        /// <returns></returns>
        public static Color FromHtml(string htmlColor)
        {
            Color empty = Color.Empty;
            if ((htmlColor != null) && (htmlColor.Length != 0))
            {
                if ((htmlColor[0] == '#') && ((htmlColor.Length == 7) || (htmlColor.Length == 4)))
                {
                    if (htmlColor.Length == 7)
                    {
                        empty = Color.FromArgb(
                            Convert.ToInt32(htmlColor.Substring(1, 2), 0x10), 
                            Convert.ToInt32(htmlColor.Substring(3, 2), 0x10), 
                            Convert.ToInt32(htmlColor.Substring(5, 2), 0x10));
                    }
                    else
                    {
                        string str = char.ToString(htmlColor[1]);
                        string str2 = char.ToString(htmlColor[2]);
                        string str3 = char.ToString(htmlColor[3]);
                        empty = Color.FromArgb(Convert.ToInt32(str + str, 0x10), Convert.ToInt32(str2 + str2, 0x10), Convert.ToInt32(str3 + str3, 0x10));
                    }
                }
                if (empty.IsEmpty && string.Equals(htmlColor, "LightGrey", StringComparison.OrdinalIgnoreCase))
                {
                    empty = Color.LightGray;
                }
            }
            return empty;
        }
    }
}
